<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/*anke 第二版接口 api*/
class AkV2Api extends  BaseApi
{
	//进出门禁
	const GetContractInfo="http://host.gymparty.net:81/SCHWebService.asmx/GetContractInfo";// 获取会员信息
	const CheckIn="http://host.gymparty.net:81/SCHWebService.asmx/CheckIn";//进场
	const ConfirmCheckOut="http://host.gymparty.net:81/SCHWebService.asmx/ConfirmCheckOut"; //出场
	//私教打卡
	const GetPTEmployeeList="http://host.gymparty.net:81/CSmart/SCHWebService.asmx/GetPTEmployeeList";// 私教列表
	const GetReservationList="http://host.gymparty.net:81/CSmart/SCHWebService.asmx/GetReservationList";//预约列表
	const DoLessonStart="http://host.gymparty.net:81/CSmart/SCHWebService.asmx/DoLessonStart"; //上课
	const DoLessonEnd="http://host.gymparty.net:81/CSmart/SCHWebService.asmx/DoLessonEnd"; //下课
	
	protected $BrandCode;//品牌id
	protected $ClubId;//健身房id
	protected $Key;//健身房key
	
	protected $shop_id;//店铺id
	
	/**
	 * 测试地址
	 * */
	 public function _initialize()
    {
//  	parent::_initialize();
    }
	/***
	 * 获取店铺名称
	 *  http://SmartGYM.com/api/AkV2Api/GetShopName/shop_id/7
	 **/
	public function GetShopName($shop_id){
		$this->before_method($shop_id);
		$mac=input("mac");
		if(!empty($mac)){
			$count=db("Equipment")->where("mac_addr='$mac' ")->count(1);
			if(empty($count)){
				//自动注册
				db("Equipment")->insert(array("mac_addr"=>$mac,"name"=>"私教平板","type"=>2,"shop_id"=>$shop_id));
			}	
		}
		$shop_name=db("Shop")->where("id=$shop_id and api_version in('anke','ocm')")->value("shop_name");
		if(!empty($shop_name)){
			return $this->ajax_success(array("shop_name"=>$shop_name));	
		}else{
			return $this->ajax_error("店铺id配置错误,或者非anke,ocm 店铺");
		}
		
	}
	/**
	 * 私教获取
	 * http://SmartGYM.com/api/AkV2Api/GetPTEmployeeList/shop_id/7
	 * */
	public  function GetPTEmployeeList($shop_id){
		$this->before_method($shop_id);
		$config_shopinfo=cache("ShopInfo_".$shop_id);
		if($config_shopinfo['api_version']=='anke'){//安科系统
			$res= post_submit_xml(self::GetPTEmployeeList,array("BrandCode"=>$this->BrandCode,"ClubId"=>$this->ClubId,"Key"=>$this->Key));
			if(empty($res)){
				return $this->ajax_error('','0003','配置错误或者私教列表为空');
			}else{
				//安科的教练
				$pt_list= json_decode($res[0],TRUE);
				if(empty($pt_list)){
					return $this->ajax_error('','0003','私教列表为空');
				}
				//如果卡号在安科系统不存在，那么就把电话号码作为卡号
				foreach ($pt_list as $k => $v) {
					if(empty($v['EmployeeCardNo'])&&empty($v['EmployeeMobile'])){
						unset($pt_list[$k]);
					 	continue;
					}
					if(empty($v['EmployeeCardNo'])){
						$pt_list[$k]['EmployeeCardNo']=$v['EmployeeMobile'];	
					}
				}
				//录入模板了的教练
				$pt_sync=db("Interface")->where("shop_id=$shop_id and owner_type=2 and card_no in(select card_no from m_face_code where shop_id=$shop_id)")->column("card_no");
				foreach ($pt_list as $key => $value) {
					 if(!in_array($value['EmployeeCardNo'],$pt_sync)){
					 	unset($pt_list[$key]);
					 }
				}
				return $this->ajax_success(array_values($pt_list));
			}
		}else if($config_shopinfo['api_version']=='ocm'){//一厘米智能管理系统
			  $employees=db("GymEmployee")->where("shop_id=$shop_id and type=3")->field("id as EmployeeID,name as EmployeeName,mobile as EmployeeMobile")->select();
			  if(empty($employees)){
			  	return $this->ajax_error('','0003','私教列表为空');
			  }
			  foreach ($employees as $key => $value) {
			  	$employees[$key]['EmployeeCardNo']=db("Interface")->where("shop_id=$shop_id and mobile='".$value['EmployeeMobile']."' and name='".$value['EmployeeName']."'")->value("card_no");
			  }
			  return $this->ajax_success($employees);
		}else if($config_shopinfo['api_version']=='vjian'){//微键
			  return $this->ajax(action('VJianApi/GetPTEmployeeList',['shop_id'=>$shop_id]));
		}
		else{
			return $this->ajax_error('','0003','api_version 暂不支持');
		}
	}
	
	/**
	 * 获取预约课程列表
	 * http://SmartGYM.com/api/AkV2Api/GetReservationList/shop_id/7/EmployeeID/AE833CA4-16C9-4B5C-B666-39BD4AE7413C/EmployeeCardNo/0723109292
	 * */
	 public function GetReservationList($shop_id,$EmployeeID,$EmployeeCardNo){
	 	$this->before_method($shop_id);
		$config_shopinfo=cache("ShopInfo_".$shop_id);
		if(empty(input("EmployeeCardNo"))||empty(input("EmployeeID"))){
	 			return $this->ajax_error("","0003","pt 卡号 为空");
		}
		$count=db("Interface")->where(" shop_id=$shop_id and owner_type=2 and card_no='".input("EmployeeCardNo")."'")->count(1);
		if($count<1){
				return $this->ajax_error("","0003","pt未录入系统或未录入特征模板！");
		}
		if($config_shopinfo['api_version']=='anke'){//安科系统
		 	$res= post_submit_xml(self::GetReservationList,array("BrandCode"=>$this->BrandCode,"ClubId"=>$this->ClubId,"Key"=>$this->Key,"EmployeeID"=>input("EmployeeID")));
			if(empty($res)){
				return $this->ajax_error('','0003','配置错误或约课列表为空');
			}else{
				return $this->ajax_success(json_decode($res[0],TRUE));
			}
		}else if($config_shopinfo['api_version']=='vjian'){//微键
			return $this->ajax(action('VJianApi/GetReservationList',['shop_id'=>$shop_id,'EmployeeID'=>$EmployeeID,'EmployeeCardNo'=>$EmployeeCardNo]));
		}else if($config_shopinfo['api_version']=='ocm'){
			$follows=db("GymPtFollow")->where("shop_id=$shop_id and pt_id=$EmployeeID and type=2 and TO_DAYS(order_date)=TO_DAYS(now())")
				->field("id,pt_id,member_id,order_time,order_date,pt_order_id,course_count,course_status")->select();
			if(empty($follows)){
				return $this->ajax_error('','','暂时未约课');
			}else{
				$list='';
				$employee=db("GymEmployee")->where("id=$EmployeeID and shop_id=$shop_id")->find();
				foreach ($follows as $key => $follow) {
					$data['PTReservationID']=$follow['id'];
					$data['EmployeeID']=$EmployeeID;
					$data['ReservationTime']=$follow['order_time'];
					if(empty($follow['course_status'])){
						$data['ReservationStatus']="未上课";	
					}elseif($follow['course_status']==1){
						$data['ReservationStatus']="已下课";
					}elseif($follow['course_status']==2){
						$data['ReservationStatus']="上课中";
					}					
					$data['ReservationEmployeeName']=$employee['name'];
					$data['EmployeeName']=$employee['name'];
					$data['MemberID']=$follow['member_id'];
					$member=db("Interface")->where("shop_id=$shop_id and member_id=".$follow['member_id'])->find();
					$data['MemberName']=$member['name'];
					$data['MemberCardNo']=$member['card_no'];
					$pt_order=db("GymPtOrder")->where("id=".$follow['pt_order_id'])->find();
					$data['LessonName']=$pt_order['course_name'];
					$data['StillNumber']=$member['surplus_num'];
					$data['ReservationNumber']=$follow['course_count'];
					$data['LessonStartTime']='';
					$data['LessonEndTime']='';
					$list[]=$data;
				}
				return $this->ajax_success($list);
			}	
				
		}else{
			return $this->ajax_error('','0003','无效的api_version');
		}
	 	
	 }
	 /**
	  * 获取上课教练的指纹和上课会员的指纹
	  * http://SmartGYM.com/api/AkV2Api/GetFingerPTAndMember/shop_id/7/EmployeeCardNo/0723109292/MemberID/58ade9ed-afa1-4b0d-8a05-53999960ef95
	  */
	 public function GetFingerPTAndMember($shop_id,$EmployeeCardNo,$MemberID,$varify_type=1,$has_txt=1){
	 	$this->before_method($shop_id);
	 	if(empty(input("EmployeeCardNo")||empty(input("MemberID")))){
	 		return $this->ajax_error("","0003","MemberID,EmployeeCardNo 为空");
	 	}else{
	 		if($varify_type==2){//获取人脸
	 			$e_card_no=input("EmployeeCardNo");
				$m_card_no=input("MemberCardNo");
				if(empty($m_card_no)){
					$card_nos=db("Interface")->where("shop_id=$shop_id and member_id='$MemberID'")->column("card_no");
					if(count($card_nos)!=1){
						return $this->ajax_error("","0003","MemberID 不唯一！");
					}else{
						$m_card_no=$card_nos[0];
					}	
				}
		 		$count=db("ModelDownRecord")->where("card_no in('$e_card_no','$m_card_no') and shop_id=$shop_id and is_down=0")->count(1);
				if($count<1){//没有更新
					if($has_txt==1){//本地有模板
			 			return $this->ajax_success(array("PTFinger"=>"","MemberFinger"=>""));
			 		}	
				}
	 		
	 			$pt_finger=db("FaceCode")->where("card_no='".input("EmployeeCardNo")."' and shop_id=$shop_id")->value("face1");
				if(empty($pt_finger)){
					return $this->ajax_error("","0003","pt未录入系统或未录入特征模板！");
				}
				$all_card_nos=explode(",", $m_card_no);
				if(count($all_card_nos)>1){
					$member_finger=db("FaceCode")->where(" shop_id=$shop_id and card_no in($m_card_no)")->value("face1");	
				}else{
					$member_finger=db("FaceCode")->where(" shop_id=$shop_id and card_no='$m_card_no'")->value("face1");	
				}
				if(empty($member_finger)){
					return $this->ajax_error("","0003","学员未录入系统或未录入特征模板！");
				}
				db("ModelDownRecord")->where("card_no in('$e_card_no','$m_card_no') and shop_id=$shop_id ")->setField(array("is_down"=>1));
	 		}else{//获取指纹
	 			$pt_finger=db("Interface")->where("card_no='".input("EmployeeCardNo")."' and shop_id=$shop_id")->value("fingerprint");
				if(empty($pt_finger)){
					return $this->ajax_error("","0003","pt未录入系统或未录入特征模板！");
				}
				$member_finger=db("Interface")->where("shop_id=$shop_id and member_id='".input("MemberID")."'")->value("fingerprint");
				if(empty($member_finger)){
					return $this->ajax_error("","0003","学员未录入系统或未录入特征模板！");
				}
	 		}
			return $this->ajax_success(array("PTFinger"=>$pt_finger,"MemberFinger"=>$member_finger));
	 	}
	}
	 /**
	  * 获取人脸url
	  * http://SmartGYM.com/api/AkV2Api/GetFaceUrlPTAndMember/shop_id/7/EmployeeCardNo/0723109292/MemberID/58ade9ed-afa1-4b0d-8a05-53999960ef95
	  */
	 public function GetFaceUrlPTAndMember($shop_id,$EmployeeCardNo,$MemberID){
	 	$this->before_method($shop_id);
	 	if(empty(input("EmployeeCardNo")||empty(input("MemberID")))){
	 		return $this->ajax_error("","0003","MemberID,EmployeeCardNo 为空");
	 	}else{
	 			$e_card_no=input("EmployeeCardNo");
				$m_card_no=db("Interface")->where("shop_id=$shop_id and member_id='$MemberID'")->value("card_no");
	 		
	 			$pt_face_url=db("FaceCode")->where("card_no='$e_card_no' and shop_id=$shop_id")->value("icon1");
				if(empty($pt_face_url)){
					return $this->ajax_error("","0003","pt未录入系统或未录入特征模板！");
				}
				$member_face_url=db("FaceCode")->where(" shop_id=$shop_id and card_no=(select card_no from m_interface where  shop_id=$shop_id and member_id='".input("MemberID")."')")->value("icon1");
				if(empty($member_face_url)){
					return $this->ajax_error("","0003","学员未录入系统或未录入特征模板！");
				}
				$url="http://".$_SERVER['SERVER_NAME']."/";
				return $this->ajax_success(array("PTFinger"=>$url.$pt_face_url,"MemberFinger"=>$url.$member_face_url));
	 	}
	 }
	
	/**
	 * 开始上课
	 * http://SmartGYM.com/api/AkV2Api/DoLessonStart/shop_id/2/EmployeeID/AE833CA4-16C9-4B5C-B666-39BD4AE7413C/MemberID/fe71c953-515e-4e83-825b-38a657ed0c4d/ReservationID/9f4d13c3-3eba-4028-96ce-3cb86cb98c45
	 * */
	 public function DoLessonStart($EmployeeID,$MemberID,$ReservationID,$shop_id){
	 	$this->before_method($shop_id);
		$config_shopinfo=cache("ShopInfo_".$shop_id);
	 	if($config_shopinfo['api_version']=='anke'){//安科系统
		 	if(empty($EmployeeID)||empty($MemberID)||empty($ReservationID)){
		 		return $this->ajax_error("","0003","EmployeeID,MemberID,ReservationID为空");
		 	}
		 	$res= post_submit_xml(self::DoLessonStart,array("BrandCode"=>$this->BrandCode,"ClubId"=>$this->ClubId,"Key"=>$this->Key,"EmployeeID"=>$EmployeeID,"MemberID"=>$MemberID,"ReservationID"=>$ReservationID));
			if(empty($res)){
				return $this->ajax_error('','0003','配置错误或者参数错误');
			}else{
				$res=json_decode($res[0],TRUE);
				if($res["Status"]==1){
					return $this->ajax_success($res["Remark"]);
				}
				return $this->ajax_error('','0003',$res["Remark"]);
			}
		}else if($config_shopinfo['api_version']=='vjian'){
			return $this->ajax(action('VJianApi/DoLessonStart',['EmployeeID'=>$EmployeeID,'MemberID'=>$MemberID,'ReservationID'=>$ReservationID,'shop_id'=>$shop_id]));
		}
		else if($config_shopinfo['api_version']=='ocm'){
			$this->_Up_Lesson($MemberID, $EmployeeID, $ReservationID, $shop_id);
		}else{
			return $this->ajax_error("","0003","api_version 版本不支持！");
		}
	 }
	 /**
	 * 开始下课
	 * http://SmartGYM.com/api/AkV2Api/DoLessonEnd/shop_id/2/EmployeeID/AE833CA4-16C9-4B5C-B666-39BD4AE7413C/MemberID/fe71c953-515e-4e83-825b-38a657ed0c4d/ReservationID/9f4d13c3-3eba-4028-96ce-3cb86cb98c45/Number/1
	 * */
	 public function DoLessonEnd($EmployeeID,$MemberID,$ReservationID,$Number,$shop_id,$PrivateCardId=''){
	 	$this->before_method($shop_id);	
		$config_shopinfo=cache("ShopInfo_".$shop_id);
	 	if($config_shopinfo['api_version']=='anke'){//安科系统
		 	if(empty($EmployeeID)||empty($MemberID)||empty($ReservationID)||empty($Number)){
		 		return $this->ajax_error("","0003","EmployeeID,MemberID,ReservationID,Number为空");
		 	}
		 	$res= post_submit_xml(self::DoLessonEnd,array("BrandCode"=>$this->BrandCode,"ClubId"=>$this->ClubId,"Key"=>$this->Key,"EmployeeID"=>$EmployeeID,"MemberID"=>$MemberID,"ReservationID"=>$ReservationID,"Number"=>$Number));
			if(empty($res)){
				return $this->ajax_error('','0003','配置错误或者参数错误');
			}else{
				$res=json_decode($res[0],TRUE);
				if($res["Status"]==1){
					return $this->ajax_success($res["Remark"]);
				}
				return $this->ajax_error('','0003',$res["Remark"]);
			}
	 	}else if($config_shopinfo['api_version']=='vjian'){
			return $this->ajax(action('VJianApi/DoLessonEnd',['EmployeeID'=>$EmployeeID,'MemberID'=>$MemberID,'ReservationID'=>$ReservationID,'Number'=>$Number,'shop_id'=>$shop_id,'PrivateCardId'=>$PrivateCardId]));
		}
	 	else if($config_shopinfo['api_version']=='ocm'){
			$this->_Down_Lesson($MemberID, $EmployeeID, $ReservationID, $Number,$shop_id);
		}else{
			return $this->ajax_error("","0003","api_version 版本不支持！");
		}	 	
	 }
	/**
	 * 取消下课
	 * http://SmartGYM.com/api/AkV2Api/CancleLessonEnd/shop_id/2/EmployeeID/AE833CA4-16C9-4B5C-B666-39BD4AE7413C/MemberID/fe71c953-515e-4e83-825b-38a657ed0c4d/ReservationID/9f4d13c3-3eba-4028-96ce-3cb86cb98c45/Number/1
	 * */
	 public function CancleLessonEnd($EmployeeID,$MemberID,$ReservationID,$Number,$shop_id,$PrivateCardId=''){
	 	$this->before_method($shop_id);	
		$config_shopinfo=cache("ShopInfo_".$shop_id);
	 	if($config_shopinfo['api_version']=='anke'){//安科系统
		 	if(empty($EmployeeID)||empty($MemberID)||empty($ReservationID)||empty($Number)){
		 		return $this->ajax_error("","0003","EmployeeID,MemberID,ReservationID,Number为空");
		 	}
			return $this->ajax_error("","0003","暂未开放！尽请期待");
//		 	$res= post_submit_xml(self::DoLessonEnd,array("BrandCode"=>$this->BrandCode,"ClubId"=>$this->ClubId,"Key"=>$this->Key,"EmployeeID"=>$EmployeeID,"MemberID"=>$MemberID,"ReservationID"=>$ReservationID,"Number"=>$Number));
//			if(empty($res)){
//				return $this->ajax_error('','0003','配置错误或者参数错误');
//			}else{
//				$res=json_decode($res[0],TRUE);
//				if($res["Status"]==1){
//					return $this->ajax_success($res["Remark"]);
//				}
//				return $this->ajax_error('','0003',$res["Remark"]);
//			}
	 	}else{
			return $this->ajax_error("","0003","api_version 版本不支持！");
		}	 	
	 }
	/**
	 * 添加自动下课记录
	 * */
	public function AutoDoLessonEndRecord(){
		$EmployeeID=input("EmployeeID");
		$EmployeeName=input("EmployeeName");
		$EmployeeCardNo=input("EmployeeCardNo");
		$MemberID=input("MemberID");
		$MemberName=input("MemberName");
		$MemberCardNo=input("MemberCardNo");
		$ReservationID=input("ReservationID");
		$ReservationName=input("ReservationName");
		$Number=input("Number");
		$shop_id=input("ShopID");
		$PrivateCardId=input("PrivateCardId");
		
	 	$this->before_method($shop_id);	
		$config_shopinfo=cache("ShopInfo_".$shop_id);
	 	if($config_shopinfo['api_version']=='anke'){//安科系统
		 	if(empty($EmployeeID)||empty($MemberID)||empty($ReservationID)||empty($Number)){
		 		return $this->ajax_error("","0003","EmployeeID,MemberID,ReservationID,Number为空");
		 	}
			$auto_time=$this->GetAutoTime($shop_id);
		 	db("AutoLessonEnd")->insert(
					array(
							"employee_id"=>$EmployeeID,
							"employee_name"=>$EmployeeName,
							"employee_card_no"=>$EmployeeCardNo,
							"member_id"=>$MemberID,
							"member_name"=>$MemberName,
							"member_card_no"=>$MemberCardNo,
							"reservation_id"=>$ReservationID,
							"reservation_name"=>$ReservationName,
							"number"=>$Number,
							"shop_id"=>$shop_id,
							"will_excute_time"=>date('Y-m-d H:i:s',strtotime("+$auto_time minute")),
							"create_time"=>date('Y-m-d H:i:s'),
						 )
			);
			return $this->ajax_success("成功");
	 	}else{
			return $this->ajax_error("","0003","api_version 版本不支持！");
		}
	}

	/**
	 * 获取店铺自动下课时间
	 * */		
	public function GetAutoTime($shop_id){
		$config1=cache("SystemSetConfig_$shop_id");
    	if(empty($config1)){
			 $config1=db("SystemSet")->where("shop_id=$shop_id")->column('code,pvalue');
			 cache("SystemSetConfig_$shop_id",$config1);
    	}
		if(isset($config1['s_s_8'])&&!empty($config1['s_s_8'])){
			return $config1['s_s_8'];
		}else{
			return "30";
		}
	}
	 //图片上传
	 public function UploadImage(){
	 	 $file = request()->file('file');
		 \think\log::write($file,"err");
	 	 if(!empty($file)){
	 	 	 $info = $file->move(ROOT_PATH . 'data' . DS . 'attendance');
			 return $this->ajax_success();
	 	 }else{
	 	 	return $this->ajax_error('','0003',"图片为空！");
	 	 }
	 }
	 /***
	  * 获取教练模板库
	  * http://SmartGYM.com/api/AkV2Api/GetCoachLib/shop_id/2/
	  **/
	 public function GetCoachLib(){
	 	$shop_id=input("shop_id",0);
		$this->before_method($shop_id);
		$list=db("FaceCode")->field("card_no,face1")->where("shop_id=$shop_id and card_no in(select card_no from m_interface where shop_id=$shop_id and owner_type=2 )")->select();
		if(empty($list)){
			return $this->ajax_error('','0003',"模板库为空");
		}else{
			return $this->ajax_success($list);	
		}
	}
	/**
	 * 根据品牌代码获取店铺列表
	 * */
	function GetListByBrandCode(){
		$brand_code=input("brand_code/s");
		if(empty($brand_code)){
			return $this->ajax_error('','0003','品牌代码为空');
		}
		$list=db("Shop")->field("id as shop_id,shop_name")->where("parent_id!=0 and parent_id=(select id from m_shop where brand_code='$brand_code' and parent_id=0)")->select();
		if(empty($list)){
				return $this->ajax_error('','0003','品牌代码错误！');
		}else{
			return $this->ajax_success($list);
		}
	}
	/**
	 * 获取根据店铺id 获取品牌代码
	 * */
	function GetBrandCodeByShopId(){
		$shop_id=input("shop_id/d");
		if(empty($shop_id)){
			return $this->ajax_error('','0003','参数错误(null)');
		}else{
			$brand_code=db("shop")->where("id=(select parent_id  from m_shop where id=$shop_id and parent_id !=0)")->value("brand_code");
			if(empty($brand_code)){
				return $this->ajax_error('','0003','品牌代码(null)');
			}else{
				return $this->ajax_success(array('brand_code'=>$brand_code));
			}
		}
	}
	/**
	 * 启动设备
	 * */
	function StartUpDeviceLog(){
		$data['shop_id']=input("shop_id/d");//店铺id
		$data['score']=input("score");//阀值
		$data['mac_addr']=input("mac_addr");//mac 地址
		$data['brand_code']=input("brand_code");//品牌代码
		$data['api_version']=input("api_version");//api 版本
		$data['soft_version']=input("soft_version");//软件版本
		$data['machine_type']=input("machine_type/d",1);//设备类型
		db("DeviceLog")->insert($data);
		return $this->ajax_success();
	}
	/**
	 * 获取私教卡列表
	 * */
	public function CardList($MemberID,$shop_id){
	 	$this->before_method($shop_id);	
		$config_shopinfo=cache("ShopInfo_".$shop_id);
	 	if($config_shopinfo['api_version']=='vjian'){//微键系统
	 		return $this->ajax(action('VJianApi/CardList',['MemberID'=>$MemberID,'shop_id'=>$shop_id]));	
		}else{
			return $this->ajax_error("","0003","api_version 版本不支持！");
		}
	 }
	/////////////////////////////////////////获取安科数据////////////////////////////////////////////////////////////////
	/**
	 * 方法前操作获取店铺信息
	 */
	function before_method($shop_id){
		if(empty($shop_id)){
			$this->ajax_error('','',"店铺id 为空");
		}else{
			$this->shop_id=$shop_id;
		}
		$shopStatus=cache("ShopStatus_".$shop_id);
		if($shopStatus===FALSE){
			cache("ShopStatus_".$shop_id,db("Shop")->where("id=".$shop_id)->value("status"));
			$shopStatus=cache("ShopStatus_".$shop_id);
		}
		if(empty($shopStatus)){
			$this->ajax_error('','','您的场馆账号异常！请和管理员联系');
		}
		/**
		 * 店铺信息
		 * */
		$config_shopinfo=cache("ShopInfo_".$shop_id);
		if(empty($config_shopinfo)){
			$config_shopinfo=db("Shop")->where("id=".$shop_id)->find();
			if(empty($config_shopinfo)){
				return $this->ajax_error('','',"店铺id 不存在");
			}else{
				cache("ShopInfo_".$shop_id,$config_shopinfo);
			}
		}
		if($config_shopinfo['api_version']=='anke'){// 安科系统
			$config=cache("ExtraConfig_".$shop_id);
	    	if(empty($config)){
				 $config=db("Shop")->where("id=".$shop_id." and api_version='anke'")->value("extra_config");
				 if(empty($config)){
				 	$this->ajax_error('','',"店铺id配置错误,或者安科配置代码错误");
				}
				 $config=json_decode($config,TRUE);
				 cache("ExtraConfig_".$shop_id,$config);
	    	} 
			if(!isset($config['BrandCode'])){
				$this->ajax_error('','',"未配置安科代码");
			}
	    	$this->BrandCode=$config['BrandCode'];
			$this->ClubId=$config['ClubID'];
			$this->Key=$config['Key'];
		}else if($config_shopinfo['api_version']=='ocm'){// 一厘米科技智能管理
			
		}
		
	}
	/**
	 * 获取合同号
	 * @param $card_no
	 * @return $data
	 * [
	 *	    {
	 *		        "ContractID": "06162ef0-7022-433e-80bd-7d9d44dc113c",
	 *		        "MemberID": "5c5313c8-aa5b-493a-8664-88e89b19a6ca",
	 *		        "MemberName": "ERCC",
	 *		        "Sex": "鐢�",
	 *		        "Mobile": "18523020102",
	 *		        "CardNo": "2238082314",
	 *		        "StartDate": "2017-10-19",
	 *		        "EndDate": "2018-10-28",
	 *		        "ContractStatus": 1,
	 *		        "MembershipType": 2,
	 *		        "MembershipTypeName": "骞存湀鍗�",
	 *		        "SurplusNum": "0",
	 *		        "StoredSumValue": "0.00"
	 *		    }
	 *		]
	 * http://smartgym.com/api/AkV2Api/GetContractInfo/card_no/0723322990/shop_id/7
	 */
	function GetContractInfo($card_no,$shop_id){
		$this->before_method($shop_id);
		$result=http_get(self::GetContractInfo,['BrandCode'=>$this->BrandCode,"ClubID"=>$this->ClubId,"CardNo"=>$card_no,"Mobile"=>"","Key"=>$this->Key]);
		if($result['flag']){
			$json= xml_json($result['data']);
			if(empty($json)){
				return template_error('配置错误或者同步数据无效(安科)');
			}else{
				if(!empty($json[0][0])){
					$result=json_decode($json[0],TRUE);
					if(empty($result)){
						return template_error("无效的卡号(安科)");
					}else{
						return template_success('成功(安科)',$result[0]);
					}
				}else{
					return template_error($this->anke_error($json[0]));
				}
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	/**
	 * 入场操作
	 * @param $card_no
	 * http://smartgym.com/api/AkV2Api/CheckIn/contract_id/4d52fed0-26ee-4d6a-856e-6d52e543a3d8/member_id/3831d4e8-425d-403d-b2bf-a019509f6917/shop_id/7/card_no/0723322990
	 */
	function CheckIn($contract_id,$member_id,$shop_id,$card_no){
		$this->before_method($shop_id);
		$result=http_get(self::CheckIn,['BrandCode'=>$this->BrandCode,"ClubID"=>$this->ClubId,"ContractID"=>$contract_id,"MemberID"=>$member_id,"Key"=>$this->Key]);
		if($result['flag']){
			$json= xml_json($result['data']);
			if(empty($json)){
				return template_error("配置错误或者卡号错误(安科)");
			}else{
				if($json[0]==1){
					return template_success("成功(安科)",$json);
				}else{
					return template_error($this->anke_error($json[0]));
				}
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	/**
	 * 出场操作
	 * @param $card_no
	 */
	function ConfirmCheckOut($card_no,$shop_id){
		$this->before_method($shop_id);
		$result=http_get(self::ConfirmCheckOut,['BrandCode'=>$this->BrandCode,"ClubID"=>$this->ClubId,"CardNo"=>$card_no,"Mobile"=>'',"Key"=>$this->Key]);
		if($result['flag']){
			$json= xml_json($result['data']);
			if(empty($json)){
				return template_error("配置错误或者卡号错误(安科)");
			}else{
				return template_success("成功(安科)",$json);
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	function anke_error($code){
          $error=[
            '1'=>"成功(安科)",
            '-1'=>"系统错误(安科)",
            '-2'=>"参数错误(安科)",
            '-3'=>"此卡为外店卡，不能在本地通用(安科)",
            '-4'=>"剩余次数为0(安科)",
            '-5'=>"已超过该会员携带的人数（安科）",
            '-6'=>"主卡不再场,副卡无法入场（安科）",
            '-7'=>'高峰时段卡，目前禁止入场(安科)',
            '-8'=>'当日利用次数已完,无法入场(安科)',
            '-9'=>'本周利用次数已完，无法入场（安科）',
            '-10'=>'本周利用次数已完，无法入场（安科）',
            '-11'=>'入场类商品不存在，无法入场（安科）',
            '-12'=>'储值卡余额不足，无法入场(安科)',
            '-13'=>'没找到有效合同，没权限入场，请重新同步会员信息（安科）',
          ];
		if(in_array($code,array_keys($error))){
			return $error[$code];
		}else{
			return "卡号不存在 或者未知的错误类型(安科)";
		}		
	}
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 上课
	 * */
	function _Up_Lesson($member_id,$pt_id,$pt_follow_id,$shop_id){
		//判断是否入场
		$this->_is_in($shop_id,$member_id);
		//课程状态
		$course_status=db("GymPtFollow")->where("id=".$pt_follow_id)->value("course_status");
		if($course_status==2){
			$this->ajax_error('','0003',"正在上课中,无法再次上课");
		}else if($course_status==1){
			$this->ajax_error('','0003',"已经下课，无法再次上课");
		}
		$pt_follow=db("GymPtFollow")->find($pt_follow_id);
		//修改课程状态
		db("GymPtFollow")->where("id=".$pt_follow_id)->setField(array("course_status"=>2));
		//私教订单
		$pt_order=db("GymPtOrder")->find($pt_follow['pt_order_id']);
		//修改课程数量			
		db("GymPtOrder")->where("id=".$pt_follow['pt_order_id'])->setField(array("last_course_time"=>input("up_time"),"surplus"=>(input("surplus",0)-input("course_count",0))));
		//插入上课记录
		db("GymCourseHistory")->insert(array(
			 "course_name"=>$pt_order["course_name"],
			 "course_count"=>$pt_follow["course_count"],
			 "shop_id"=>$shop_id,
			 "pt_order_id"=>$pt_order['id'],
			 "pt_follow_id"=>$pt_follow['id'],
			 "up_time"=>date("Y-m-d H:i:s"),
			 "member_id"=>$member_id,
			 "pt_id"=>$pt_id
		));	
		$this->ajax_success();
	} 
	/*下课*/
	function _Down_Lesson($member_id,$pt_id,$pt_follow_id,$number,$shop_id){
			//判断是否入场
			//$this->_is_in($shop_id,$member_id);
			//课程状态
			$course_status=db("GymPtFollow")->where("id=".$pt_follow_id)->value("course_status");
			if(empty($course_status)){
				$this->ajax_error('','0003',"还未上课，无法下课");
			}else if($course_status==1){
				$this->ajax_error('','0003',"已经下课，无法再次下课");
			}
			db("GymPtFollow")->where("id=$pt_follow_id")->setField(array("course_status"=>1));
			//完成私教课次数
			db("GymMember")->where("id=$member_id")->setInc("over_private_lesson");	
			//插入下课记录
			db("GymCourseHistory")->where("pt_follow_id=$pt_follow_id")->update(array( "down_time"=>date("Y-m-d H:i:s")));
			$this->ajax_success();					
	}
	//判断是否入场
	function _is_in($shop_id,$member_id){
		$count=db("BehaviorLog")->where("shop_id=$shop_id and member_id=$member_id and TO_DAYS(create_time)=TO_DAYS(now())")->count(1);
		if($count>0){
		}else{
			$this->ajax_error('','0003',"您还没有入场");
		}
	}
}
